Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 28/31 Β· 107.4 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Exception handling

JavaScript includes a try ... catch ... finally exception handling statement to handle run-time errors.

The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:

try {
// Statements in which exceptions might be thrown
} catch(errorValue) {
// Statements that execute in the event of an exception
} finally {
// Statements that execute afterward either way
}

Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block can throw(errorValue), if it does not want to handle a specific error.

In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected.

Either the catch or the finally clause may be omitted. The catch argument is required.

The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java:

try { statement; }
catch (e if e == "InvalidNameException") { statement; }
catch (e if e == "InvalidIdException") { statement; }
catch (e if e == "InvalidEmailException") { statement; }
catch (e) { statement; }

In a browser, the onerror event is more commonly used to trap exceptions.

onerror = function (errorValue, url, lineNr) {...; return true;};

Native functions and methods

eval (expression)

Evaluates the first parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However, eval represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.cite-ref-deve-eval-27-0[27]

> (function foo() {
... var x = 7;
... console.log("val " + eval("x + 2"));
... })();
val 9
undefined


──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────